package cn.iocoder.yudao.boot.common.validate;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {EnumAnno.EnumValidator.class})
public @interface EnumAnno {

    String message() default "";

    // 作用参考@Validated和@Valid的区别
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 目标枚举类
     */
    Class<?> enumClass() default Class.class;

    /**
     * 是否忽略空值
     */
    boolean ignoreEmpty() default true;


    class EnumValidator implements ConstraintValidator<EnumAnno, Object> {

        // 枚举校验注解
        private EnumAnno annotation;

        @Override
        public void initialize(EnumAnno constraintAnnotation) {
            annotation = constraintAnnotation;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            boolean result = false;

            Class<?> clazz = annotation.enumClass();
            boolean ignoreEmpty = annotation.ignoreEmpty();

            // target为枚举，并且value有值，或者不忽视空值，才进行校验
            if (clazz.isEnum() && (value != null || !ignoreEmpty)) {

                Object[] objects = clazz.getEnumConstants();
                for (Object obj : objects) {
                    // 使用此注解的枚举类需要重写toString方法，改为需要验证的值
                    if (obj.toString().equals(String.valueOf(value))) {
                        result = true;
                        break;
                    }
                }
            } else {
                result = true;
            }
            return result;
        }
    }
}